<?php

use think\Db;
use think\Request;

use dousdk\AuthAppDouyin;
use commonsdk\Tools;

/**
 * 不重复组合
 */
if (!function_exists("getSortCartList")) {
    function getSortCartList($array, $level = -1, &$list = [])
    {
        for ($i = 0; $i < count($array); $i++) {
            if ($level < 0) {
                //第一级直接输出对应数字
                $list[] = (string)$array[$i];
            } else {
                $values = $array[$i];
                //根据等级组装前几位
                for ($k = 0; $k < $level; $k++) {
                    $values .= ',' . $array[$i + $k + 1];
                }
                $j = 0;
                //循环拼合最后一位
                for ($n = ($i + $level + 1); $n < count($array); $n++) {
                    $j++;
                    $first = $values; // 组合上几位
                    $first .= ',' . $array[$n];
                    $list[] = $first;

                }
                //到最后一位结束递归
                if ($j == 1) {
                    break;
                }
            }

        }
        //长度大于等级+2停止递归
        if (($level + 2) < count($array)) {
            getSortCartList($array, $level + 1, $list);
        }
        return $list;
    }
}


if (!function_exists("recom")) {
    function recom($arr)
    {
        if (count($arr) >= 2) {
            $tmparr = array();
            $arr1 = array_shift($arr);
            $arr2 = array_shift($arr);
            foreach ($arr1 as $k1 => $v1) {
                foreach ($arr2 as $k2 => $v2) {
                    $tmparr[] = $v1 . $v2;
                }
            }
            array_unshift($arr, $tmparr);
            $arr = recom($arr);
        } else {
            return $arr;
        }
        return $arr;
    }
}

if (!function_exists("getArrSet")) {
    function getArrSet($arrs, $_current_index = -1)
    {
//总数组
        static $_total_arr;
//总数组下标计数
        static $_total_arr_index;
//输入的数组长度
        static $_total_count;
//临时拼凑数组
        static $_temp_arr;

//进入输入数组的第一层，清空静态数组，并初始化输入数组长度
        if ($_current_index < 0) {
            $_total_arr = array();
            $_total_arr_index = 0;
            $_temp_arr = array();
            $_total_count = count($arrs) - 1;
            getArrSet($arrs, 0);
        } else {
//循环第$_current_index层数组
            foreach ($arrs[$_current_index] as $v) {
//如果当前的循环的数组少于输入数组长度
                if ($_current_index < $_total_count) {
//将当前数组循环出的值放入临时数组
                    $_temp_arr[$_current_index] = $v;
//继续循环下一个数组
                    getArrSet($arrs, $_current_index + 1);

                } //如果当前的循环的数组等于输入数组长度(这个数组就是最后的数组)
                else if ($_current_index == $_total_count) {
//将当前数组循环出的值放入临时数组
                    $_temp_arr[$_current_index] = $v;
//将临时数组加入总数组
                    $_total_arr[$_total_arr_index] = $_temp_arr;
//总数组下标计数+1
                    $_total_arr_index++;
                }

            }
        }

        return $_total_arr;
    }
}

/**
 * url地址拼接完整地址
 */
if (!function_exists("images_url")) {

    function images_url($url)
    {
        return request()->domain(true) . $url;
    }

}

if (!function_exists("create_open_id")) {
    function create_open_id($head = "", $length = '', $char = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-')
    {
        if (!is_int($length) || $length < 0) {
            return '$length 必须为Int类型';
        }

        $string = '';
        for ($i = $length; $i > 0; $i--) {
            $string .= $char[mt_rand(0, strlen($char) - 1)];
        }

        return $head . $string;
    }
}

if (!function_exists("pdo_update")) {

    function pdo_update($db = "", $data = [], $where = [])
    {
        return Db::name($db)->where($where)->update($data);
    }

}

if (!function_exists("pdo_get")) {

    function pdo_get($db = "", $where = [])
    {
        return Db::name($db)->where($where)->find();
    }

}
if (!function_exists("pdo_insert")) {

    function pdo_insert($db = "", $data = [])
    {
        return Db::name($db)->insert($data);
    }

}

if (!function_exists("pdo_insertid")) {

    function pdo_insertid($db = "")
    {
        return Db::name($db)->getLastInsID();
    }

}


//if (!function_exists("json")) {
//
//    function json($data = '', $code = 0, $msg = '提交成功！')
//    {
//        header('Content-Type:application/json; charset=utf-8');
//        $result = array(
//            'code' => $code,
//            'msg' => $msg,
//            'data' => $data
//        );
//        exit(json_encode($result));
//    }
//
//}
if (!function_exists("jsont")) {

    function jsont($data = '', $code = 0, $msg = '')
    {
        header('Content-Type:application/json; charset=utf-8');
        $data['token'] = (isset($_COOKIE['formtoken'])) ? $_COOKIE['formtoken'] : "";
        $result = array(
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        );
        exit(json_encode($result));
    }

}


if (!function_exists("json_old")) {

    function json_old($data = '', $code = 0, $msg = '提交成功！') {
        header('Content-Type:application/json; charset=utf-8');
        $result = array(
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        );
        exit(json_encode($result));
    }

}

if (!function_exists("check_formtoken")) {

    function check_formtoken()
    {
        return true;
        $_GPC = input();
        if ($_COOKIE['formtoken'] == $_GPC['data']['token']) {
            $token = md5(rand(1, 999));
            setcookie('formtoken', $token, time() + 7200, '/');
            unset($_GPC['data']['token']);
            return $token;
        } else {
            json(array(
                'code' => 1,
                'msg' => '您已经提交过了！',
                'data' => ''
            ));
        }
    }

}

function ihttp_allow_host($host)
{
    global $_W;
    if (strexists($host, '@')) {
        return false;
    }
    $pattern = '/^(10|172|192|127)/';
    if (preg_match($pattern, $host) && isset($_W['setting']['ip_white_list'])) {
        $ip_white_list = $_W['setting']['ip_white_list'];
        if ($ip_white_list && isset($ip_white_list[$host]) && !$ip_white_list[$host]['status']) {
            return false;
        }
    }

    return true;
}


function ihttp_build_curl($url, $post, $extra, $timeout)
{
    if (!function_exists('curl_init') || !function_exists('curl_exec')) {
        return error(1, 'curl扩展未开启');
    }

    $urlset = ihttp_parse_url($url);
    if (is_error($urlset)) {
        return $urlset;
    }

    if (!empty($urlset['ip'])) {
        $extra['ip'] = $urlset['ip'];
    }

    $ch = curl_init();
    if (!empty($extra['ip'])) {
        $extra['Host'] = $urlset['host'];
        $urlset['host'] = $extra['ip'];
        unset($extra['ip']);
    }
    curl_setopt($ch, CURLOPT_URL, $urlset['scheme'] . '://' . $urlset['host'] . (empty($urlset['port']) || '80' == $urlset['port'] ? '' : ':' . $urlset['port']) . $urlset['path'] . (!empty($urlset['query']) ? $urlset['query'] : ''));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    @curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    if ($post) {
        if (is_array($post)) {
            $filepost = false;
            foreach ($post as $name => &$value) {
                if (version_compare(phpversion(), '5.5') >= 0 && is_string($value) && '@' == substr($value, 0, 1)) {
                    $post[$name] = new CURLFile(ltrim($value, '@'));
                }
                if ((is_string($value) && '@' == substr($value, 0, 1)) || (class_exists('CURLFile') && $value instanceof CURLFile)) {
                    $filepost = true;
                }
            }
            if (!$filepost) {
                $post = http_build_query($post);
            }
        }
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    }
    if (!empty($GLOBALS['_W']['config']['setting']['proxy'])) {
        $urls = parse_url($GLOBALS['_W']['config']['setting']['proxy']['host']);
        if (!empty($urls['host'])) {
            curl_setopt($ch, CURLOPT_PROXY, "{$urls['host']}:{$urls['port']}");
            $proxytype = 'CURLPROXY_' . strtoupper($urls['scheme']);
            if (!empty($urls['scheme']) && defined($proxytype)) {
                curl_setopt($ch, CURLOPT_PROXYTYPE, constant($proxytype));
            } else {
                curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
                curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
            }
            if (!empty($GLOBALS['_W']['config']['setting']['proxy']['auth'])) {
                curl_setopt($ch, CURLOPT_PROXYUSERPWD, $GLOBALS['_W']['config']['setting']['proxy']['auth']);
            }
        }
    }
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSLVERSION, 1);
    if (defined('CURL_SSLVERSION_TLSv1')) {
        curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
    }
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1');
    if (!empty($extra) && is_array($extra)) {
        $headers = array();
        foreach ($extra as $opt => $value) {
            if (strexists($opt, 'CURLOPT_')) {
                curl_setopt($ch, constant($opt), $value);
            } elseif (is_numeric($opt)) {
                curl_setopt($ch, $opt, $value);
            } else {
                $headers[] = "{$opt}: {$value}";
            }
        }
        if (!empty($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
    }

    return $ch;
}

if (!function_exists("ihttp_request")) {

    function ihttp_request($url, $post = '', $extra = array(), $timeout = 60)
    {
        if (function_exists('curl_init') && function_exists('curl_exec') && $timeout > 0) {
            $ch = ihttp_build_curl($url, $post, $extra, $timeout);
            if (is_error($ch)) {
                return $ch;
            }
            $data = curl_exec($ch);
            $status = curl_getinfo($ch);
            $errno = curl_errno($ch);
            $error = curl_error($ch);
            curl_close($ch);
            if ($errno || empty($data)) {
                return error($errno, $error);
            } else {
                return ihttp_response_parse($data);
            }
        }
        $urlset = ihttp_parse_url($url, true);
        if (!empty($urlset['ip'])) {
            $urlset['host'] = $urlset['ip'];
        }

        $body = ihttp_build_httpbody($url, $post, $extra);

        if ('https' == $urlset['scheme']) {
            $fp = ihttp_socketopen('ssl://' . $urlset['host'], $urlset['port'], $errno, $error);
        } else {
            $fp = ihttp_socketopen($urlset['host'], $urlset['port'], $errno, $error);
        }
        stream_set_blocking($fp, $timeout > 0 ? true : false);
        stream_set_timeout($fp, ini_get('default_socket_timeout'));
        if (!$fp) {
            return error(1, $error);
        } else {
            fwrite($fp, $body);
            $content = '';
            if ($timeout > 0) {
                while (!feof($fp)) {
                    $content .= fgets($fp, 512);
                }
            }
            fclose($fp);

            return ihttp_response_parse($content, true);
        }
    }

}
if (!function_exists("ihttp_get")) {

    function ihttp_get($url)
    {
        return ihttp_request($url);
    }

}

if (!function_exists("douYinUrl")) {
    /**
     * 获取抖音授权url
     */
    function douYinUrl($url = '')
    {
        if(!$url) $url = 'https://open.douyin.com/platform/oauth/connect/?client_key=awoks0h55n4xvu1d&response_type=code&scope=user_info,mobile_alert,video.create,data.external.item&redirect_uri=https://devdy.422wsdq.com?id=2';
        return $url;
    }
}


if (!function_exists("mkdirs")) {
    function mkdirs($dir, $mode = 0777)
    {
        if (is_dir($dir) || @mkdir($dir, $mode)) return TRUE;
        if (!mkdirs(dirname($dir), $mode)) return FALSE;
        return @mkdir($dir, $mode);
    }
}

if (!function_exists("jsonp")) {

    function jsonp($data = '', $messages = '请求成功')
    {
//        header('Content-Type:application/json; charset=utf-8');
        $result = array(
            'code' => 200,
            'message' => $messages,
            'data' => $data
        );
        \think\facade\Log::info('请求响应数据：');
        \think\facade\Log::info($result);
        return Response::create($result, 'json', 200, [], []);
//        exit(json_encode($result));
    }

}

if (!function_exists("jsonpp")) {

    function jsonpp($data = '', $count = 0) {
        header('Content-Type:application/json; charset=utf-8');
        $result = array(
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $data
        );
        exit(json_encode($result));
    }

}

/**
 * 抖音解密手机号码
 */
if (!function_exists("decryptdy")) {
    function decryptdy($encrypted_mobile, $client_secret)
    {
        $iv = substr($client_secret, 0, 16);
        return openssl_decrypt($encrypted_mobile, 'aes-256-cbc', $client_secret, 0, $iv);
    }
}

if (!function_exists("jsonp_error")) {

    function jsonp_error($code = 422, $messages = '参数错误')
    {
//        header('Content-Type:application/json; charset=utf-8');
        $result = array(
            'code' => $code,
            'message' => $messages,
            'data' => []
        );
        return Response::create($result, 'json', $code, [], []);
//        exit(json_encode($result));
    }

}

if (!function_exists("get_redirect_url")) {

    function get_redirect_url($url)
    {
        $header = get_url_headers(trim($url), 10);
        // print_r($header);exit;
        if (($header) < 3) {
            $header = get_headers(trim($url), true);
        }
        if (strpos($header[0], '301') !== false || strpos($header[0], '302') !== false) {
            if (is_array($header['Location'])) {
                return $header['Location'][count($header['Location']) - 1];
            } else {
                return $header['Location'];
            }
        } else {
            return $url;
        }
    }

}

if (!function_exists("get_sysset")) {

    function get_sysset($set = '')
    {

        $data = pdo_get('sysset', array('id' => 1));
        $sets = isset($data['sets']) ? json_decode($data['sets'], true) : array();
        //基础设置
        isset($sets['basic']) or $sets['basic'] = array(
            'platform_name' => '霸屏',
            'logo' => '/upload/logo.png',
            'apitoken' => '',
            'client_key' => '',
            'client_secret' => '',
            'ali_keyid' => '',
            'ali_keysecret' => '',
            'ali_bucketname' => ''
        );
        isset($sets['recharge']) or $sets['recharge'] = array(
            'basenum' => '100',
            'prices' => "100\r\n300\r\n500\r\n800\r\n1000\r\n1500\r\n3000\r\n5000"
        );
        $sets['agent_level'] = '';
        if ($set == '') {
            return $sets;
        } else {
            return $sets[$set];
        }
    }

}
if (!function_exists("get_abs_path")) {

    function get_abs_path($path)
    {
        if (stristr($path, 'http') == false) {
            return $this->request->domain(true) . $path;
        } else {
            return $path;
        }
    }

}
if (!function_exists("get_upload_data")) {

    function get_upload_data($result)
    {
        $result['uploadtype'] = 'local';
        $result['mp4uploadurl'] = '/commons/Upfile/mp4';
        $result['mediauploadurl'] = '/commons/Upfile/media';
        $result['uploadurl'] = '/commons/upfile/index';
        $result['cdnurl'] = '';
        return $result;
    }

}
if (!function_exists("create_order_sn")) {

    function create_order_sn()
    {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        return $yCode[intval(date('Y')) - 2020] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
    }

}

if (!function_exists("createPoster")) {

    /**
     * 生成宣传海报
     * @param array  参数,包括图片和文字
     * @param string $filename 生成海报文件名,不传此参数则不生成文件,直接输出图片
     * @return [type] [description]
     */
    function createPoster($config = array(), $filename = "")
    {
        //如果要看报什么错，可以先注释调这个header
        if (empty($filename))
            header("content-type: image/png");
        $imageDefault = array(
            'left' => 0,
            'top' => 0,
            'right' => 0,
            'bottom' => 0,
            'width' => 100,
            'height' => 100,
            'opacity' => 100
        );
        $textDefault = array(
            'text' => '',
            'left' => 0,
            'top' => 0,
            'fontSize' => 32, //字号
            'fontColor' => '255,255,255', //字体颜色
            'angle' => 0,
        );
        $background = $config['background']; //海报最底层得背景
        //背景方法
        if (isset($config['stream'])) {
            $backgroundInfo = getimagesizefromstring($background);
            $backgroundFun = 'imagecreatefromstring';
        } else {
            $backgroundInfo = getimagesize($background);
            $backgroundFun = 'imagecreatefrom' . image_type_to_extension($backgroundInfo[2], false);
        }
        $background = $backgroundFun($background);
        $backgroundWidth = isset($config['width']) ? $config['width'] : imagesx($background);  //背景宽度
        $backgroundHeight = isset($config['height']) ? $config['height'] : imagesy($background);  //背景高度
        $imageRes = imageCreatetruecolor($backgroundWidth, $backgroundHeight);
        $color = imagecolorallocate($imageRes, 0, 0, 0);
        imagefill($imageRes, 0, 0, $color);
        // imageColorTransparent($imageRes, $color);  //颜色透明
        imagecopyresampled($imageRes, $background, 0, 0, 0, 0, $backgroundWidth, $backgroundHeight, imagesx($background), imagesy($background));
        //处理了图片
        if (!empty($config['image'])) {
            foreach ($config['image'] as $key => $val) {
                $val = array_merge($imageDefault, $val);

                $info = getimagesizefromstring($val['url']);
                $function = 'imagecreatefromstring';

                $res = $function($val['url']);
                $resWidth = $info[0];
                $resHeight = $info[1];
                if (isset($val['radius'])) {
                    $res = imageRadius($res);
                    //建立画板 ，缩放图片至指定尺寸
                    $canvas = imagecreatetruecolor($val['width'], $val['height']);
                    imagesavealpha($canvas, true);
                    $bg = imagecolorallocate($canvas, 200, 200, 200);
                    imagecolortransparent($canvas, $bg);
                    imagefill($canvas, 0, 0, $bg);
                } else {
                    //建立画板 ，缩放图片至指定尺寸
                    $canvas = imagecreatetruecolor($val['width'], $val['height']);
                    imagefill($canvas, 0, 0, $color);
                }
                //关键函数，参数（目标资源，源，目标资源的开始坐标x,y, 源资源的开始坐标x,y,目标资源的宽高w,h,源资源的宽高w,h）
                imagecopyresampled($canvas, $res, 0, 0, 0, 0, $val['width'], $val['height'], $resWidth, $resHeight);
                $val['left'] = $val['left'] < 0 ? $backgroundWidth - abs($val['left']) - $val['width'] : $val['left'];
                $val['top'] = $val['top'] < 0 ? $backgroundHeight - abs($val['top']) - $val['height'] : $val['top'];
                //放置图像
                imagecopymerge($imageRes, $canvas, $val['left'], $val['top'], $val['right'], $val['bottom'], $val['width'], $val['height'], $val['opacity']); //左，上，右，下，宽度，高度，透明度
            }
        }
        //处理文字
        if (!empty($config['text'])) {
            foreach ($config['text'] as $key => $val) {
                $val = array_merge($textDefault, $val);
                list($R, $G, $B) = explode(',', $val['fontColor']);
                $fontColor = imagecolorallocate($imageRes, $R, $G, $B);
                $val['left'] = $val['left'] < 0 ? $backgroundWidth - abs($val['left']) : $val['left'];
                $val['top'] = $val['top'] < 0 ? $backgroundHeight - abs($val['top']) : $val['top'];
                imagettftext($imageRes, $val['fontSize'], $val['angle'], $val['left'], $val['top'], $fontColor, $val['fontPath'], $val['text']);
            }
        }
        //生成图片
        if (!empty($filename)) {
            $res = imagejpeg($imageRes, $filename, 90); //保存到本地
            imagedestroy($imageRes);
            if (!$res)
                return false;
            return $filename;
        } else {
            imagejpeg($imageRes);     //在浏览器上显示
            imagedestroy($imageRes);
        }
    }

}
if (!function_exists("imageRadius")) {

    /**
     * 图片圆角
     * @param bool $target
     * @param bool $circle
     * @return resource
     */
    function imageRadius($target = false)
    {
        $w = imagesx($target);
        $h = imagesy($target);
        $w = min($w, $h);
        $h = $w;
        $img = imagecreatetruecolor($w, $h);
        imagesavealpha($img, true);
        $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
        imagefill($img, 0, 0, $bg);
        $radius = $w / 2;
        $r = $radius;
        $x = 0;
        while ($x < $w) {
            $y = 0;
            while ($y < $h) {
                $rgbColor = imagecolorat($target, $x, $y);
                if ($radius <= $x && $x <= $w - $radius || $radius <= $y && $y <= $h - $radius) {
                    imagesetpixel($img, $x, $y, $rgbColor);
                } else {
                    $y_x = $r;
                    $y_y = $r;
                    if (($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y) <= $r * $r) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                    $y_x = $w - $r;
                    $y_y = $r;
                    if (($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y) <= $r * $r) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                    $y_x = $r;
                    $y_y = $h - $r;
                    if (($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y) <= $r * $r) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                    $y_x = $w - $r;
                    $y_y = $h - $r;
                    if (($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y) <= $r * $r) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                }
                ++$y;
            }
            ++$x;
        }
        return $img;
    }

}
if (!function_exists("gettoken")) {

    function gettoken($input)
    {
        return base64UrlEncode(hash_hmac('sha256', json_encode($input), 'mglb052282020', true));
    }

}
if (!function_exists("base64UrlEncode")) {

    function base64UrlEncode($input)
    {
        return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
    }

}
if (!function_exists("base64UrlDecode")) {

    function base64UrlDecode($input)
    {
        $remainder = strlen($input) % 4;
        if ($remainder) {
            $addlen = 4 - $remainder;
            $input .= str_repeat('=', $addlen);
        }
        return base64_decode(strtr($input, '-_', '+/'));
    }

}
if (!function_exists("asyn_http_get")) {

    //非阻塞http请求
    function asyn_http_get($url)
    {
        // $response = array();
        $chs = curl_multi_init();
        // $map = array();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        // curl_setopt ($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOSIGNAL, true);
        // 忽略SSL证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_multi_add_handle($chs, $ch);
        // $map[strval($ch)] = $url;
        do {
            if (($status = curl_multi_exec($chs, $active)) != CURLM_CALL_MULTI_PERFORM) {
                if ($status != CURLM_OK) {
                    break;
                } //如果没有准备就绪，就再次调用curl_multi_exec
                while ($done = curl_multi_info_read($chs)) {
                    curl_multi_remove_handle($chs, $done['handle']);
                    curl_close($done['handle']);
                    //如果仍然有未处理完毕的句柄，那么就select
                    if ($active > 0) {
                        curl_multi_select($chs, 1); //此处会导致阻塞大概1秒。
                    }
                }
            }
        } while ($active > 0); //还有句柄处理还在进行中
        curl_multi_close($chs);
    }

}

if (!function_exists("ihttp_parse_url")) {
    function ihttp_parse_url($url, $set_default_port = false)
    {
        if (empty($url)) {
            return error(1);
        }
        $urlset = parse_url($url);
        if (!empty($urlset['scheme']) && !in_array($urlset['scheme'], array('http', 'https'))) {
            return error(1, '只能使用 http 及 https 协议');
        }
        if (empty($urlset['path'])) {
            $urlset['path'] = '/';
        }
        if (!empty($urlset['query'])) {
            $urlset['query'] = "?{$urlset['query']}";
        }
        if (empty($urlset['host'])) {
            $current_url = parse_url($GLOBALS['_W']['siteroot']);
            $urlset['host'] = $current_url['host'];
            $urlset['scheme'] = $current_url['scheme'];
            $urlset['path'] = $current_url['path'] . 'web/' . str_replace('./', '', $urlset['path']);
            $urlset['ip'] = '127.0.0.1';
        } elseif (!ihttp_allow_host($urlset['host'])) {
            return error(1, 'host 非法');
        }

        if ($set_default_port && empty($urlset['port'])) {
            $urlset['port'] = 'https' == $urlset['scheme'] ? '443' : '80';
        }

        return $urlset;
    }
}

function strexists($string, $find)
{
    return !(false === strpos($string, $find));
}

function is_error($data)
{
    if (empty($data) || !is_array($data) || !array_key_exists('errno', $data) || (array_key_exists('errno', $data) && 0 == $data['errno'])) {
        return false;
    } else {
        return true;
    }
}


function ihttp_response_parse($data, $chunked = false)
{
    $rlt = array();

    $pos = strpos($data, "\r\n\r\n");
    $split1[0] = substr($data, 0, $pos);
    $split1[1] = substr($data, $pos + 4, strlen($data));

    $split2 = explode("\r\n", $split1[0], 2);
    preg_match('/^(\S+) (\S+) (.*)$/', $split2[0], $matches);
    $rlt['code'] = !empty($matches[2]) ? $matches[2] : 200;
    $rlt['status'] = !empty($matches[3]) ? $matches[3] : 'OK';
    $rlt['responseline'] = !empty($split2[0]) ? $split2[0] : '';
    $header = explode("\r\n", $split2[1]);
    $isgzip = false;
    $ischunk = false;
    foreach ($header as $v) {
        $pos = strpos($v, ':');
        $key = substr($v, 0, $pos);
        $value = trim(substr($v, $pos + 1));
        if (isset($rlt['headers'][$key]) && is_array($rlt['headers'][$key])) {
            $rlt['headers'][$key][] = $value;
        } elseif (!empty($rlt['headers'][$key])) {
            $temp = $rlt['headers'][$key];
            unset($rlt['headers'][$key]);
            $rlt['headers'][$key][] = $temp;
            $rlt['headers'][$key][] = $value;
        } else {
            $rlt['headers'][$key] = $value;
        }
        if (!$isgzip && 'content-encoding' == strtolower($key) && 'gzip' == strtolower($value)) {
            $isgzip = true;
        }
        if (!$ischunk && 'transfer-encoding' == strtolower($key) && 'chunked' == strtolower($value)) {
            $ischunk = true;
        }
    }
    if ($chunked && $ischunk) {
        $rlt['content'] = ihttp_response_parse_unchunk($split1[1]);
    } else {
        $rlt['content'] = $split1[1];
    }
    if ($isgzip && function_exists('gzdecode')) {
        $rlt['content'] = gzdecode($rlt['content']);
    }

    $rlt['meta'] = $data;
    if ('100' == $rlt['code']) {
        return ihttp_response_parse($rlt['content']);
    }

    return $rlt;
}


if (!function_exists("dy_oauth_userinfo")) {

    //非阻塞http请求
    function dy_oauth_userinfo($client_key, $client_secret)
    {

        $_GPC = input();
        if (session('userinfo') == "") {
            $dy = new AuthAppDouyin;
            $dy->client_key = $client_key;
            $dy->client_secret = $client_secret;
            $userinfo = $dy->getWebOauthInfo(request()->domain(true) . $_SERVER['REQUEST_URI']);
            if (!empty($userinfo)) {
                session('openid', $userinfo['open_id']);
                session('fans', $userinfo);
                session('userinfo', base64_encode(serialize($userinfo)));
                return 'success';
            } else {
                return '授权登录失败';
            }

        } else {
            $userinfo = unserialize(base64_decode(session('userinfo')));
            if (!empty($userinfo['nickname'])) {
                session('openid', $userinfo['open_id']);
                session('fans', $userinfo);
                return 'success';
            }
        }
    }

}

if (!function_exists("convertUrlQuery")) {

    /**
     * 解析url中参数信息，返回参数数组
     */
    function convertUrlQuery($query)
    {
        $urlarr = parse_url($query);
        $queryParts = explode('&', $urlarr['query']);

        $params = array();
        foreach ($queryParts as $param) {
            $item = explode('=', $param);
            $params[$item[0]] = $item[1];
        }

        return $params;
    }

}
if (!function_exists("getUrlQuery")) {

    function getUrlQuery($array_query)
    {
        $tmp = array();
        foreach ($array_query as $k => $param) {
            $tmp[] = $k . '=' . $param;
        }
        $params = implode('&', $tmp);
        return $params;
    }

}
if (!function_exists("is_iphone")) {

    function is_iphone()
    {
        $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
        if (strpos($agent, 'iphone') || strpos($agent, 'ipad')) {
            return true;
        } else {
            return false;
        }
    }

}
if (!function_exists("is_mobile")) {

    function is_mobile()
    {
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
            return true;
        }
        //如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if (isset($_SERVER['HTTP_VIA'])) {
            //找不到为flase,否则为true
            return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
        }
        //判断手机发送的客户端标志,兼容性有待提高
        if (isset($_SERVER['HTTP_USER_AGENT'])) {
            $clientkeywords = array('nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh', 'lg', 'sharp', 'sie-',
                'philips', 'panasonic', 'alcatel', 'lenovo', 'iphone', 'ipod', 'blackberry', 'meizu', 'android', 'netfront', 'symbian',
                'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi', 'openwave', 'nexusone', 'cldc', 'midp', 'wap', 'mobile'
            );
            // 从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
                return true;
            }
        }
        //协议法，因为有可能不准确，放到最后判断
        if (isset($_SERVER['HTTP_ACCEPT'])) {
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false ||
                    (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') <
                        strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
                return true;
            }
        }
        return false;
    }

}
if (!function_exists("get_url_headers")) {

    function get_url_headers($url, $timeout = 10)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_NOBODY, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        $data = curl_exec($ch);
        $data = preg_split('/\n/', $data);
        $data = array_filter(array_map(function ($data) {
            $data = trim($data);
            if ($data) {
                $data = preg_split('/:\s/', trim($data), 2);
                $length = count($data);
                switch ($length) {
                    case 2:
                        return array($data[0] => $data[1]);
                        break;
                    case 1:
                        return $data;
                        break;
                    default:
                        break;
                }
            }
        }, $data));
        sort($data);
        foreach ($data as $key => $value) {
            $itemKey = array_keys($value)[0];
            if (is_int($itemKey)) {
                $data[$key] = $value[$itemKey];
            } elseif (is_string($itemKey)) {
                $data[$itemKey] = $value[$itemKey];
                unset($data[$key]);
            }
        }
        $first = array_shift($data);
        $data[0] = $first;
        return $data;
    }

}


/**
 * 获取视频时长
 */
if (!function_exists("video_time")) {
    function video_time($file)
    {
        ob_start();

        passthru(sprintf(FFMPEG_PATH, $file)); //passthru()类似exec()

        $info = ob_get_contents();

        ob_end_clean();

// 通过使用输出缓冲，获取到ffmpeg所有输出的内容。
        $ret = array();
// Duration: 01:24:12.73, start: 0.000000, bitrate: 456 kb/s
        if (preg_match("/Duration: (.*?), start: (.*?), bitrate: (\d*) kb\/s/", $info, $match)) {
            $ret['duration'] = $match[1]; // 提取出播放时间

            return $ret;

        }

        return "";

    }
}